package com.itc.dispatch.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itc.common.core.domain.R;
import com.itc.common.core.utils.BeanCopyUtils;
import com.itc.common.core.utils.StringUtils;
import com.itc.common.security.utils.SecurityUtils;
import com.itc.dispatch.common.Constents;
import com.itc.dispatch.common.FindAndProcessParent;
import com.itc.dispatch.domain.AlarmCentre;
import com.itc.dispatch.domain.AlarmConfig;
import com.itc.dispatch.domain.AlarmOperatingRecord;
import com.itc.dispatch.domain.UserConfig;
import com.itc.dispatch.domain.dto.AlarmCentreDto;
import com.itc.dispatch.domain.dto.AlarmCentrePageDto;
import com.itc.dispatch.domain.dto.AlarmOperatingRecordPageDto;
import com.itc.dispatch.domain.dto.AlarmTimeDto;
import com.itc.dispatch.domain.vo.*;
import com.itc.dispatch.service.*;
import com.itc.dispatch.mapper.AlarmCentreMapper;
import com.itc.system.api.RemoteSystemService;
import com.itc.system.api.domain.SysDept;
import com.itc.system.api.domain.dto.SysDeptCheckDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author 智少
* @description 针对表【alarm_centre】的数据库操作Service实现
* @createDate 2024-07-29 11:49:11
*/
@Service
public class AlarmCentreServiceImpl extends ServiceImpl<AlarmCentreMapper, AlarmCentre>
    implements AlarmCentreService{

    @Autowired
    public AlarmRuleService alarmRuleService;

    @Autowired
    public AlarmOperatingRecordService operatingRecordService;

    @Autowired
    @Lazy
    public AlarmConfigService alarmConfigService;

    @Autowired
    public  FindAndProcessParent findAndProcessParent;

    @Autowired
    public UserConfigService userConfigService;

    @Resource
    public RemoteSystemService remoteSystemService;

    @Override
    public R<Page<AlarmCentre>> getPage(Page page, AlarmCentrePageDto pageDto) {
        //暂时按全部数据展示，不用只显示最高等级
        if(!SecurityUtils.isAdmin(SecurityUtils.getUserId())){
            //超管显示全部,其他用户只显示当前用户需要处理的
            List<Long> deptIds = SecurityUtils.getLoginUser().getDeptIds();
            if(deptIds != null && deptIds.size() > 0){
                pageDto.setLimitDeptIds(deptIds);
            }
        }
        List<Long> deptIds = new LinkedList<>();
        deptIds.add(101L);
        pageDto.setLimitDeptIds(deptIds);
        if(pageDto.getIsImport() != null && pageDto.getIsImport().intValue() == 1){
            //查询所有重要告警的配置信息
            List<AlarmConfig> AlarmConfigs = alarmConfigService.getBaseMapper().selectList(
                    new LambdaQueryWrapper<AlarmConfig>()
                    .eq(AlarmConfig::getIsImport,1)
                    .eq(AlarmConfig::getDelete,0)
                    .eq(AlarmConfig::getStatus,1)
            );
            if(AlarmConfigs.size() > 0){
                pageDto.setConfigIds(AlarmConfigs.stream().map(AlarmConfig::getId).collect(Collectors.toList()));
            }
        }
        if(pageDto.getBigAlarmStatus() != null){
            List<Integer> bigAlarmStatusList = new LinkedList<>();
            if(pageDto.getBigAlarmStatus().intValue() == 1){
                bigAlarmStatusList.add(0);
                bigAlarmStatusList.add(1);
            }else{
                bigAlarmStatusList.add(2);
                bigAlarmStatusList.add(3);
                bigAlarmStatusList.add(4);
            }
            pageDto.setBigAlarmStatusList(bigAlarmStatusList);
        }

        Page<AlarmCentre> resultPage = this.baseMapper.getAlarmPage(page,pageDto);
        return R.ok(resultPage);
    }

    @Override
    @Transactional
    public R operation(AlarmCentreDto dto) {
        Long userId = SecurityUtils.getUserId();
        AlarmCentre alarmCentre = this.baseMapper.selectById(dto.getId());
        if (alarmCentre == null){
            return R.fail("数据有误");
        }
        alarmCentre.setAlarmStatus(dto.getOperation());
        this.baseMapper.updateById(alarmCentre);
        //记录当前操作人员
        AlarmOperatingRecord alarmOperatingRecord = new AlarmOperatingRecord();
        if (dto.getOperation() == 1){
            alarmOperatingRecord.setOpTableType(0);
        }else {
            alarmOperatingRecord.setOpTableType(1);
        }
        alarmOperatingRecord.setCreateTime(LocalDateTime.now().toString());
        alarmOperatingRecord.setAlarmCentreId(dto.getId());
        alarmOperatingRecord.setUserName(SecurityUtils.getUsername());
        //查询席位
        ArrayList<Long> longS = new ArrayList<>();
        longS.add(dto.getDeptChildId());
        SysDeptCheckDto sysDeptCheckDto = new SysDeptCheckDto();
        sysDeptCheckDto.setDeptIds(longS);
        R<List<SysDept>> seatListByDept = remoteSystemService.getSeatListByDeptId(sysDeptCheckDto);
        for (SysDept datum : seatListByDept.getData()) {
            alarmOperatingRecord.setDeptChildName(datum.getDeptName());
            alarmOperatingRecord.setDeptName(datum.getParentDept());
        }
        operatingRecordService.save(alarmOperatingRecord);
        //更新用户记录表
        UserConfig one = userConfigService.getById(userId);
        if (one == null){
            UserConfig userConfig = new UserConfig();
            userConfig.setUserId(userId);
            userConfig.setCentreId(dto.getId().toString());
            if (dto.getOperation() == 0){
                //新增用户配置表
                userConfig.setIsConfirm(0);
            }else {
                userConfig.setIsDis(0);
            }
            userConfigService.save(userConfig);
            return R.ok(null,"操作成功");
        }else {
            //更新用户配置表
            String newCentreId = one.getCentreId()+","+dto.getId();
            one.setCentreId(newCentreId);
            if (dto.getOperation() == 0){
                //新增用户配置表
                one.setIsConfirm(0);
            }else {
                one.setIsDis(0);
            }
            userConfigService.updateById(one);
            return R.ok(null,"操作成功");
        }
    }
    @Override
    public R<Page<AlarmOperatingRecord>> getOperationPage(Page page, AlarmOperatingRecordPageDto dto) {
        //获取确认记录表
        LambdaQueryWrapper<AlarmOperatingRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AlarmOperatingRecord::getAlarmCentreId,dto.getAlarmCentreId());
        if (dto.getOpTableType().intValue() == Constents.Int_0){
            queryWrapper.eq(AlarmOperatingRecord::getOpTableType,0);
        }else {
            //获取处置记录表
            queryWrapper.eq(AlarmOperatingRecord::getOpTableType, 1);
        }
        Page page1 = operatingRecordService.page(page, queryWrapper);
        return R.ok(page1);
    }

    @Override
    public List<AlarmCentreFlightVo> getFlightAlarmList(List<String> flightIds) {
        List<AlarmCentreFlightVo> alarmList = this.baseMapper.getFlightAlarmList(flightIds);
        return alarmList;
    }

    @Override
    public R<AlarmCentre> getAlarmDetail(Long alarmId) {
        AlarmCentre alarmCentre = this.baseMapper.selectById(alarmId);
        if(alarmCentre == null){
            return R.fail("告警信息异常");
        }
        if(StringUtils.isNotBlank(alarmCentre.getAlarmIds())){
            //查询关联的预警
            List<AlarmCentre> childList = this.baseMapper.selectList(
                    new LambdaQueryWrapper<AlarmCentre>()
                            .in(AlarmCentre::getId,alarmCentre.getAlarmIds().split(","))
            );
            alarmCentre.setChildAlarmList(childList);
        }
        if(StringUtils.isNotBlank(alarmCentre.getFlowIds())){
            //查询关联的预警
            List<AlarmCentre> childList = this.baseMapper.selectList(
                    new LambdaQueryWrapper<AlarmCentre>()
                            .in(AlarmCentre::getId,alarmCentre.getAlarmIds().split(","))
            );
            alarmCentre.setChildAlarmList(childList);
        }

        return null;
    }

    @Override
    public R<List<StatusStatesVo>> dataListGrade(AlarmTimeDto dto) {
        ArrayList<StatusStatesVo> dataStatisticsVoArrayList = new ArrayList<>();
        int [] alarmStatus={1,2,3,4};
//        if (dto.getAlarmBeginTime() == null && dto.getAlarmEndTime() == null){
//            //默认统计最近两天的数据
//            LocalDateTime towDaysTime = LocalDateTime.now().minusDays(2);
//            dto.setAlarmBeginTime(towDaysTime.toString());
//            dto.setAlarmEndTime(LocalDateTime.now().toString());
//        }
        for (int i = 1; i <= alarmStatus.length; i++) {
            List<AlarmStatusStatisticsVo> alarmStatusStatisticsVos = this.baseMapper.alarmStatusList(i, dto);
            StatusStatesVo dataStatisticsVo = new StatusStatesVo();
            dataStatisticsVo.setAlarmGrade(i);
            dataStatisticsVo.setStatusStatisticsList(alarmStatusStatisticsVos);
            dataStatisticsVoArrayList.add(dataStatisticsVo);
        }
        return R.ok(dataStatisticsVoArrayList);
    }

    @Override
    public R<List<TypeStatesVo>> dataListType(AlarmTimeDto dto) {
//        if (dto.getAlarmBeginTime() == null && dto.getAlarmEndTime() == null){
//            //默认统计最近两天的数据
//            LocalDateTime towDaysTime = LocalDateTime.now().minusDays(2);
//            dto.setAlarmBeginTime(towDaysTime.toString());
//            dto.setAlarmEndTime(LocalDateTime.now().toString());
//        }
        ArrayList<TypeStatesVo> typeStatesVos = new ArrayList<>();
        HashSet<String> alarmTypeSet = new HashSet<>();
        List<AlarmCentre> alarmCentres = this.baseMapper.selectList(null);
        for (AlarmCentre alarmCentre : alarmCentres) {
            String alarmType = alarmCentre.getAlarmType();
            alarmTypeSet.add(alarmType);
        }
        for (String alarmType : alarmTypeSet) {
            List<AlarmTypeStatisticsVo> alarmTypeStatisticsVos = this.baseMapper.alarmTypeList(alarmType, dto);
            TypeStatesVo typeStatesVo = new TypeStatesVo();
            typeStatesVo.setAlarmType(alarmType);
            typeStatesVo.setTypeStatisticsList(alarmTypeStatisticsVos);
            typeStatesVos.add(typeStatesVo);
        }
        return R.ok(typeStatesVos);
    }

}




